/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package sites

import (
	"github.com/skip2/go-qrcode"
	"github.com/fogleman/gg"
	"image/jpeg"
	"fmt"
	"os"
	"path/filepath"
)

const fonts = "library/fonts/Deng.ttf"

func GenerateQrcode(qrsize, qrTitleFont int, subID, subTitle, answerImgDir, answer, qrcodeUrl, srcImage string) (file string, err error) {
	file = filepath.Join(answerImgDir, subID+"-"+answer+".jpg")
	_, e := os.Stat(file)
	// 如果文件已存在则跳过
	if !os.IsNotExist(e) {
		return file, nil
	}

	// 生成二维码图片
	if q, err := qrcode.New(qrcodeUrl + "?id="+ subID, qrcode.Medium); err != nil {
		return "", err
	} else {
		qrcodeImg := q.Image(qrsize)

		src, err := gg.LoadImage(srcImage)
		if err != nil {
			return "", err
		}
		// 加载背景图
		dc := gg.NewContextForImage(src)
		height := dc.Height()
		rectHeight := qrsize + 10
		x := float64(35)
		y := float64(height-rectHeight - 5)
		// 画底部长方形
		dc.DrawRectangle(x, y, float64(dc.Width() - 70), float64(rectHeight))
		dc.SetRGB(1, 1, 1)
		dc.Fill()
		// 在长方形中画二维码
		x += 10
		y += 5
		dc.DrawImage(qrcodeImg, int(x), int(y))

		// 画二维码主题标题
		qrTitleFontFace, err := gg.LoadFontFace(fonts, float64(qrTitleFont))
		if err != nil {
			return "", err
		}
		dc.SetFontFace(qrTitleFontFace)
		dc.SetRGBA(1, 0, 0, 1)
		x += float64(qrsize) + 20
		y += 20 + float64(qrTitleFont)
		dc.DrawStringAnchored(subTitle, x, y, 0, 0)

		// 画二维码说明文字
		dc.SetRGBA(0, 0, 0, 1)
		y += float64(qrTitleFont) + 10
		dc.DrawStringAnchored("长按识别二维码 快来测试吧~", float64(x), float64(y), 0, 0)

		dc.Clip()
		//file := filepath.Join(subID + "-" + key + ".jpg")
		f, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0777)
		if err != nil {
			return "", err
		}
		defer f.Close()
		fmt.Printf("create file: %s\n", file)
		err = jpeg.Encode(f, dc.Image(), &jpeg.Options{Quality: 90})
		if err != nil {
			return "", err
		}
		return file, nil
	}
}
